Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

137
Visualizações
How to stop a program execution with "throw" in javascript?

I'm resuming javascript studies now and I came across a problem. I have a Customer class that receives customer data in the constructor and validates it before assigning it to its respective properties. When the phone number is incorrect, an exception is thrown which in turn must stop the execution of the entire program, however, this is the problem. I'm throwing the exception and treating it with try/catch but the program continues anyway, here's the code:

// Customer class

import { Library } from './Library.js';
import { books } from './books.js';
import chalk from 'chalk';

export class Customer {
    #name;
    #birthdate;
    #email;
    #phone;
    #code;

    constructor(name, birthdate, email, phone) {
        this.#name = name;
        this.#birthdate = birthdate;
        this.#email = email;
        this.#phone = this.#validatePhone(phone);
        this.rented = [];
        this.#code = Math.trunc(Math.random() * 99999); // MUST BE READABLE, ONLY!
    }

    get name() {
        return this.#name;
    }

    get birthdate() {
        return this.#birthdate;
    }

    get email() {
        return this.#email;
    }

    get phone() {
        return this.#phone;
    }

    set name(name) {
        this.#name = name;
    }

    set birthdate(birthdate) {
        this.#birthdate = birthdate;
    }

    set email(email) {
        this.#email = email;
    }

    set phone(phone) {
        this.#phone = phone;
    }

    async rentBoook(title, days) {
        const search = await Library.searchBook(title);
        if(search.length === 0) throw 'This book doesn\'t exist!';

        return await Library.rentBook('O Ar', this, days);
    }

    #validatePhone(phone) {
        try {
            const pattern = /(\(?[0-9]{2}\)?)\s?([0-9]{5})-?([0-9]{4})/;
            if(!pattern.test(phone)) throw 'Invalid phone number!';

            return phone;
        }catch(err) {
            console.log(chalk.red(err));
        }

    }
}
   // Index

    import chalk from 'chalk';
    import { Customer } from './Customer.js';

    const customer = new Customer('John Doe', '20-04-04', 'r@r.com', '(99) 9999-99999');

    customer.rentBoook('O Ar', 7)
    .then(r => console.log(chalk.green('Book rented with success!')))
    .catch(err => console.log(chalk.red(err)));
    // Output

    "Invalid phone number!"
    "Book rented with success!"
about 4 years ago · Santiago Gelvez
1 Respostas
Responde à pergunta

0

Phone validation should be handled in rentBook method, as validation didn't handled inside the rentBook & happened for #phone prop assignment (#phone will become undefined), both the method execute independent of one another.

For this case, will get expected result, when validation done inside rentBook before Library.search

async rentBoook(title, days) {
       ....
       validatePhone()
       ...
}

remove try catch in validatePhone Method & use try..catch in rentBook if needed

Hope this helps

about 4 years ago · Santiago Gelvez Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda